package com.example.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.bo.AdminUserDetails;
import com.example.bo.RedisUserInfo;
import com.example.bo.UserSaveDetails;
import com.example.domain.CmsPermission;
import com.example.domain.CmsUser;
import com.example.service.ICmsUserService;
import com.example.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.ArrayList;
import java.util.List;

/**
 * <h3>duty-test1</h3>
 * <p></p>
 *
 * @author : zhengyue
 * @date : 2020-03-24 10:39
 **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ICmsUserService cmsUserService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserSaveDetails userSaveDetails;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
        //基于token，不需要session
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
                //白名单
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/api-docs").permitAll()
                .antMatchers("websocket/**").permitAll()
                .antMatchers("/user/login", "/user/register").permitAll()
                //跨域请求options请求放行
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                //任何请求需要验证
                .anyRequest().authenticated()
                .and()
                //jwt 过滤器
                .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        //禁用缓存
        http.headers().cacheControl();
        //添加自定义未授权和未登录结果返回
        http.exceptionHandling()
                //用来解决认证过的用户访问无权限资源时的异常
                .accessDeniedHandler(new AdminAccessDeniedHandler())
                //用来解决匿名用户访问无权限资源时的异常
                .authenticationEntryPoint(new AdminAuthenticationEntryPoint());
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(getPasswordEncoder());
    }

    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        //获取登陆用户信息
        return username -> {
            CmsUser user = cmsUserService.getOne(new QueryWrapper<CmsUser>().lambda()
                    .eq(CmsUser::getNumber, username));
            if(ObjectUtil.isNotEmpty(user)) {
                RedisUserInfo redisUserInfo = JSON.parseObject((String)redisUtil.get(username), RedisUserInfo.class);
                if(!ObjectUtil.isNotEmpty(redisUserInfo)) {
                    redisUserInfo = new RedisUserInfo();
                }
                List<CmsPermission> permissionList = redisUserInfo.getPermissionList();
                if(permissionList == null) {
                    permissionList = new ArrayList<>();
                }
                System.out.println(JSONUtil.toJsonStr(permissionList));
                userSaveDetails.setCmsUser(user);
                return new AdminUserDetails(user, permissionList);
            }
            throw new UsernameNotFoundException("用户名或密码错误");
        };
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }
}
